//
//  RootViewController.m
//  XMPP
//
//  Created by  江志磊 on 15-3-6.
//  Copyright (c) 2015年 江 志磊. All rights reserved.
//

#import "RootViewController.h"
#import "QFXmppManager.h"//单例，封装了与xmpp服务器的交互逻辑
#import "FriendsViewController.h"

@interface RootViewController ()

@end

@implementation RootViewController

#define kUserKey   @"user"
#define kPassKey   @"pass"

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //如果用户名和密码在本地存在，直接显示在textField上
    NSUserDefaults *deaults = [NSUserDefaults standardUserDefaults];
    NSString *user = [deaults objectForKey:kUserKey];
    NSString *pass = [deaults objectForKey:kPassKey];
    if (user&&pass) {
        _userNameField.text = user;
        _passwordField.text = pass;
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//注册
- (IBAction)registerBtnClicked:(id)sender{
    if (_userNameField.text.length==0||_passwordField.text.length==0) {
        NSLog(@"信息书写不全!");
        return;
    }
    //根据用户名和密码向服务器发起注册
    [[QFXmppManager shareInstance] registerUser:_userNameField.text withPassword:_passwordField.text withCompletion:^(BOOL ret, NSError *err) {
       //ret 如果注册成功 返回Yes
        if (ret==YES) {
            NSLog(@"register successed!");
         //成功
         //将用户名和密码存储起来
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:_userNameField.text forKey:kUserKey];
            [defaults setObject:_passwordField.text forKey:kPassKey];
            [defaults synchronize];
        }else{
            if (err) {
                NSLog(@"register error:%@",err.localizedDescription);
            }
        }
    }];
}
//登录 (用已经在服务器注册成功的账号进行登录操作)
- (IBAction)loginBtnClicked:(id)sender {
    if (_userNameField.text.length==0||_passwordField.text.length==0) {
        NSLog(@"信息不全!");
        return;
    }
    //进行登录操作
    [[QFXmppManager shareInstance] loginUser:_userNameField.text withPassword:_passwordField.text withCompletion:^(BOOL ret, NSError *err) {
        if (ret==YES) {
            NSLog(@"登录成功!");
            //跳转到好友列表界面
            FriendsViewController *friends = [[FriendsViewController alloc] init];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:friends];
            [self presentViewController:nav animated:YES completion:^{
                
            }];
        }else{
            //失败
            if (err) {
                NSLog(@"login error:%@",err.localizedDescription);
            }
        }
    }];
}
//收键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_userNameField resignFirstResponder];
    [_passwordField resignFirstResponder];
}


@end
